package com.monlyu.bo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.monlyu.exception.MsgException;
import com.monlyu.model.CountPhotoModel;
import com.monlyu.model.GradeManuscriptModel;
import com.monlyu.model.ManuscriptModel;
import com.monlyu.model.Program2GaoJianModel;
import com.monlyu.model.ProgrammingModel;
import com.monlyu.model.SearchManuscriptModel;
import com.monlyu.util.DateUtil;
import com.monlyu.util.MathUtil;
import com.monlyu.util.StringUtil;
import com.monlyu.util.WebOptUtil;
import com.monlyu.varables.PermVar;
import com.monlyu.vo.GaoJian2Reporter;
import com.monlyu.vo.ManuScAudit;
import com.monlyu.vo.Manuscript;
import com.monlyu.vo.ProStaffInfo;
import com.monlyu.vo.Progm2GaoJian;
import com.monlyu.vo.Programming;
import com.monlyu.vo.User;

/*******************************************************************************
 * 
 * <b>功能描述☞</b><br>
 * 
 * <b>开发公司☞</b>重庆唯尼科技有限公司<br>
 * <b>版权☞</b>本文件归重庆唯尼科技有限公司所有<br>
 * <b>项目名☞</b>news<br>
 * <b>文件路径☞</b>com.monlyu.bo.ProgrammingBo.java<br>
 * <b>开发日期☞</b>2010-2-11 <br>
 * 
 * @author chendan
 * @since JDK 5
 * @version 1.0.8
 * 
 ******************************************************************************/
@Repository(value = "programmingBo")
public class ProgrammingBo extends BaseBo {
	private RoleBo roleBo;
	private EnumsBo enumsBo;
	private StaffScoreBo staffScoreBo;
	private ManuscriptBo manuscriptBo;

	public void setManuscriptBo(ManuscriptBo manuscriptBo) {
		this.manuscriptBo = manuscriptBo;
	}

	public void setStaffScoreBo(StaffScoreBo staffScoreBo) {
		this.staffScoreBo = staffScoreBo;
	}

	public void setRoleBo(RoleBo roleBo) {
		this.roleBo = roleBo;
	}

	public void setEnumsBo(EnumsBo enumsBo) {
		this.enumsBo = enumsBo;
	}

	/**
	 * 查询编排的节目单
	 * 
	 * @param programming
	 * @param begin
	 *            开始时间
	 * @param end
	 *            结束时间
	 * @return
	 * @since chendan 2010-2-11
	 */
	public List getPrograms(Programming programming, Date beginDate,
			Date endDate) {
		StringBuilder hql = new StringBuilder();
		hql.append("from com.monlyu.vo.Programming p where 1=1 ");
		List<Object> args = new ArrayList<Object>();
		if (programming != null) {
			if (programming.getColumn() != null) {
				hql.append(" and p.column=?");
				args.add(programming.getColumn());
			}
		}
		if (beginDate != null) {
			hql.append(" and p.date>=?");
			args.add(beginDate);
		}
		if (endDate != null) {
			hql.append(" and p.date<?");
			args.add(DateUtil.addDay(endDate, 1));
		}
		hql.append(" order by p.id desc");
		return dao.find(hql.toString(), args.toArray());
	}

	/**
	 * 根据编排日期和编排栏目查询编排的节目单，唯一值
	 * 
	 * @param programming
	 * @return
	 * @since chendan 2010-2-15
	 */
	public Programming getProgramming(Programming programming) {
		if (programming == null) {
			throw new MsgException("查询新闻编排的条件不能为空");
		} else if (programming.getId() == null
				&& programming.getColumn() == null) {
			throw new MsgException("编排栏目不能为空");
		} else if (programming.getId() == null && programming.getDate() == null) {
			throw new MsgException("编排日期不能为空");
		}
		List objList = getPrograms(programming, programming.getDate(),
				programming.getDate());
		if (objList != null && objList.size() > 0) {
			programming = (Programming) objList.get(0);
		}
		return programming;
	}

	/**
	 * 创建编排的节目单
	 * 
	 * @param programming
	 * @param idlist
	 *            选择的稿件id号
	 * @since chendan 2010-2-15
	 */
	public void createProgramming(Programming programming, String idlist) {
		if (!roleBo.checkPermission(PermVar.PROGRAMMING_SELECT)) {
			throw new MsgException("对不起，您没有栏目稿件编排的权限。");
		}
		programming.setRecorder(curUser());
		programming.setRecorderDate(DateUtil.now());
		dao.insertOrUpdate(programming);// 先保存，接下来要用生成的id号
		// 生成栏目稿件
		String[] manuscripts = idlist.split(",");
		for (int i = 0; i < manuscripts.length; i++) {
			Progm2GaoJian progm2GaoJian = new Progm2GaoJian();
			Manuscript manuscript = (Manuscript) dao.findOne(
					"from com.monlyu.vo.Manuscript m where m.id=?", new Long(
							manuscripts[i]));
			progm2GaoJian.setManuscript(manuscript);
			progm2GaoJian.setOrder(i + 1);
			progm2GaoJian.setProgramming(programming);
			dao.insertOrUpdate(progm2GaoJian);
		}
		// 生成新闻编排人员信息表
		ProStaffInfo proStaffInfo = new ProStaffInfo();
		proStaffInfo.setProgramming(programming);
		dao.insertOrUpdate(proStaffInfo);
	}

	/**
	 * 组装栏目所有的稿件成map对象
	 * 
	 * @param progId
	 * @param isManuscript
	 *            是否依据稿件的id做为map的key,true为是,false则以Progm2GaoJian的id作为Key
	 * @return
	 * @since chendan 2010-3-1
	 */
	public Map<Long, Progm2GaoJian> getProgm2GaoJians(Long progId,
			boolean isManuscript) {
		String hql = "from com.monlyu.vo.Progm2GaoJian p where p.programming.id=?";
		List<Progm2GaoJian> progm2GaoJians = dao.find(hql, progId);
		// 把查出来的已编排稿件装入map中，方便后面的查询，用稿件id号作为key，用progm2GaoJian对象作为value
		Map<Long, Progm2GaoJian> map = Maps.newHashMap();
		for (Iterator<Progm2GaoJian> it = progm2GaoJians.iterator(); it
				.hasNext();) {
			Progm2GaoJian progm2GaoJian = it.next();
			if (isManuscript) {
				map.put(progm2GaoJian.getManuscript().getId(), progm2GaoJian);
			} else {
				map.put(progm2GaoJian.getId(), progm2GaoJian);
			}
		}
		return map;
	}

	/**
	 * 出像统计
	 * 
	 * @param programming
	 * @param beginDate
	 * @param endDate
	 * @param userId
	 * @return
	 * @since chendan 2010-3-15
	 */
	public List<CountPhotoModel> countPhoto(Programming programming,
			Date beginDate, Date endDate, String userId) {
		// 查栏目
		List progms = getPrograms(programming, beginDate, endDate);
		StringBuilder hql = new StringBuilder();
		List<Object> args = Lists.newArrayList();
		hql
				.append("from com.monlyu.vo.Progm2GaoJian p where (p.kouBo like ? or "
						+ " p.daoYu like ? or  p.bianHouYu like ?) ");
		args.add("," + userId + ",");
		args.add("," + userId + ",");
		args.add("," + userId + ",");
		boolean flag = false;
		// 依次添加栏目编号
		for (Iterator<Programming> it = progms.iterator(); it.hasNext();) {
			if (!flag) {
				hql.append(" and (p.programming.id in (?");
				args.add(it.next().getId());
				flag = true;
			} else {
				hql.append(" ,?");
				args.add(it.next().getId());
				flag = true;
			}
		}
		if (flag) {
			hql.append("))");
		}
		List progm2 = dao.find(hql.toString(), args.toArray());
		if(StringUtil.isTrimEmpty(userId)){
		    throw new MsgException("请选择用户");
		}
		User user = dao.get(User.class, Long.parseLong(userId));
		List<CountPhotoModel> countList = Lists.newArrayList();
		// 组装统计的对象
		for (Iterator<Progm2GaoJian> iterator = progm2.iterator(); iterator
				.hasNext();) {
			Progm2GaoJian pGaoJian = iterator.next();
			if (pGaoJian.getKouBo() != null
					&& pGaoJian.getKouBo().indexOf("," + userId + ",") >= 0) {
				CountPhotoModel cPhotoModel = new CountPhotoModel();
				cPhotoModel.setUser(user);
				cPhotoModel.setDate(pGaoJian.getProgramming().getDate());
				cPhotoModel.setColumn(pGaoJian.getProgramming().getColumn());
				cPhotoModel.setType("口播");
				countList.add(cPhotoModel);
			}
			if (pGaoJian.getDaoYu() != null
					&& pGaoJian.getDaoYu().indexOf("," + userId + ",") >= 0) {
				CountPhotoModel cPhotoModel = new CountPhotoModel();
				cPhotoModel.setUser(user);
				cPhotoModel.setDate(pGaoJian.getProgramming().getDate());
				cPhotoModel.setColumn(pGaoJian.getProgramming().getColumn());
				cPhotoModel.setType("导语");
				countList.add(cPhotoModel);
			}
			if (pGaoJian.getBianHouYu() != null
					&& pGaoJian.getBianHouYu().indexOf("," + userId + ",") >= 0) {
				CountPhotoModel cPhotoModel = new CountPhotoModel();
				cPhotoModel.setUser(user);
				cPhotoModel.setDate(pGaoJian.getProgramming().getDate());
				cPhotoModel.setColumn(pGaoJian.getProgramming().getColumn());
				cPhotoModel.setType("编后语");
				countList.add(cPhotoModel);
			}
		}
		return countList;
	}

	/**
	 * 修改编排的节目单
	 * 
	 * @param programming
	 * @param idlist
	 *            选择的稿件id号
	 * @param audit
	 *            是否是审核操作，true为是
	 * @throws UnsupportedEncodingException
	 * @since chendan 2010-2-15
	 */
	// 如果是修改，先判断栏目有没有审核，如果已审核，看有没有审核权限，如果有，才能修改，否则提示无此权限
	// 如果是审核，先判断权限，再修改栏目内容，再修改栏目的审核状态及审核人信息
	public void updateProg(Programming programming, String idlist, boolean audit) {
		if (!audit && !roleBo.checkPermission(PermVar.PROGRAMMING_SELECT)) {
			throw new MsgException("对不起，您没有栏目稿件编排的权限。");
		} else if (!audit && !roleBo.checkPermission(PermVar.PROGRAMMING_AUDIT)) {
			throw new MsgException("对不起，您没有栏目稿件审核的权限。");
		}
		Programming dbPrgrm = getProgramming(programming.getId());
		String[] manuscripts = idlist.split(",");
		// 先将编排好的稿件查询出来，依次维护序号，如果相同，则跳过，否则修改，并做标记，对于没有维护的序号，删除掉
		Map<Long, Progm2GaoJian> map = getProgm2GaoJians(programming.getId(),
				true);
		// 依次维护编排顺序
		for (int i = 0; i < manuscripts.length; i++) {
			Manuscript manuscript = (Manuscript) dao.findOne(
					"from com.monlyu.vo.Manuscript m where m.id=?", new Long(
							manuscripts[i]));
			if (manuscript == null) {
				throw new MsgException("选择稿件出错");
			}
			Progm2GaoJian progm2GaoJian = map.get(manuscript.getId());
			if (progm2GaoJian == null) {
				// 此稿件没有选择过，需要创建一条记录
				progm2GaoJian = new Progm2GaoJian();
				progm2GaoJian.setManuscript(manuscript);
				progm2GaoJian.setProgramming(programming);
				// progm2GaoJian.setTiYao(manuscript.getTitle());
				// 只有审核时，对于选用的稿件，才记录使用次数
				if (audit || dbPrgrm.isAudit()) {
					manuscript.setTimes(manuscript.getTimes() + 1);
				}
			} else {
				// 如果此稿件已经编排过，则删除map中的记录
				map.remove(manuscript.getId());
				// 如果此稿件已经编排过了，但是是第一次审核，同样记录使用次数，否则不改变使用次数
				if (audit && dbPrgrm.getAuditUser() == null) {
					manuscript.setTimes(manuscript.getTimes() + 1);

				}
			}
			manuscriptBo.setMansUsedDate(manuscript);
			dao.insertOrUpdate(manuscript);
			// 重新设置顺序号
			progm2GaoJian.setOrder(i + 1);
			dao.insertOrUpdate(progm2GaoJian);
		}
		// 删除剩余没有再次编排的稿件
		for (Iterator<Progm2GaoJian> it = map.values().iterator(); it.hasNext();) {
			// 当审核时， 移除稿件时，稿件的使用次数减少1
			if (audit || dbPrgrm.isAudit()) {
				Progm2GaoJian progm2GaoJian = it.next();
				Manuscript manuscript = progm2GaoJian.getManuscript();
				manuscript.setTimes(manuscript.getTimes() - 1);
				manuscriptBo.setMansUsedDate(manuscript);
				dao.insertOrUpdate(manuscript);
				dao.delete(progm2GaoJian);
			}
		}
		// 审核新闻栏目
		if (audit) {
			// 2010-7-1 为了防止audit字段记录其他类型字符而影响后面流程
			if (programming.isAudit()) {
				dbPrgrm.setAudit(true);
			} else {
				dbPrgrm.setAudit(false);
			}
			// 如果不是第一次审核，则不记录后面的审核人员
			if (dbPrgrm.getAuditDate() == null) {
				dbPrgrm.setAuditDate(DateUtil.now());
			}
			if (dbPrgrm.getAuditUser() == null) {
				dbPrgrm.setAuditUser(curUser());
			}
			dbPrgrm.setAuditRemark(programming.getAuditRemark());
			dao.insertOrUpdate(dbPrgrm);
		}
	}

	/**
	 * 查询新闻节目单的编排信息
	 * 
	 * @param progmId
	 * @return
	 * @since chendan 2010-2-15
	 */
	public List searchProgm2GaoJian(Long progmId) {
		String hql = "from com.monlyu.vo.Progm2GaoJian p where p.programming.id=? order by p.order";
		List gaojians = dao.find(hql, progmId);
		List<Progm2GaoJian> progLsit = Lists.newArrayList();
		for (Iterator<Progm2GaoJian> it = gaojians.iterator(); it.hasNext();) {
			Progm2GaoJian progm = it.next();
			Manuscript manuscript = progm.getManuscript();
			manuscript
					.setReportorName(getManuscriptReporter(manuscript.getId()));
			progm.setDaoYuName(parseUesrIdToName(progm.getDaoYu()));
			progm.setKouBoName(parseUesrIdToName(progm.getKouBo()));
			progm.setBianHouYuName(parseUesrIdToName(progm.getBianHouYu()));
			progLsit.add(progm);
		}
		return progLsit;
	}

	public String getManuscriptReporter(Long ManuscriptId) {
		List users = dao
				.find(
						"select u.name from com.monlyu.vo.GaoJian2Reporter g,com.monlyu.vo.User u where g.reporter.id=u.id and g.manuscript.id=?",
						ManuscriptId);
		StringBuilder str = new StringBuilder();
		for (Iterator iterator = users.iterator(); iterator.hasNext();) {
			str.append((String) iterator.next() + "|");
		}
		if (str.toString().length() > 0) {
			str.deleteCharAt(str.toString().length() - 1);
		}
		return str.toString();
	}

	/**
	 * 检测栏目审核人员是否是当前用户
	 * 
	 * @param programming
	 * @return
	 * @since chendan 2010-3-11
	 */
	public boolean checkUser(Programming programming) {
		if (programming.getAuditUser() == null) {
			return true;
		}
		return curUser().getId().equals(programming.getAuditUser().getId());
	}

	/**
	 * 查询待审串联单
	 * 
	 * @return
	 * @since chendan 2010-3-21
	 */
	public List getAuditProgramming() {
		// 检查权限
		if (roleBo.checkPermission(PermVar.PROGRAMMING_AUDIT)) {
			String hql = " from com.monlyu.vo.Programming p where p.audit=?";
			return dao.find(hql, Boolean.valueOf(false));
		}
		return null;
	}

	/**
	 * 编辑节目单中的稿件信息
	 * 
	 * @param contentInfo
	 * @param programming
	 * @since chendan 2010-2-15
	 */
	public void editProg2GaoJian(String contentInfo, Programming programming) {
		if (!roleBo.checkPermission(PermVar.PROGRAMMING_DETAIL)) {
			throw new MsgException("对不起，您没有栏目信息编排的权限。");
		}
		String[] strs = contentInfo.split(";");
		Map<Long, Progm2GaoJian> map = getProgm2GaoJians(programming.getId(),
				false);
		for (int i = 0; i < strs.length; i++) {
			String[] strs2 = strs[i].split("\\|");
			if (Integer.parseInt(strs2[0]) > 0) {
				// 依次设置各字段的值，顺序号为i
				Progm2GaoJian progm2GaoJian = map.get(Long.parseLong(strs2[0]));
				if (progm2GaoJian != null) {
					map.remove(Long.parseLong(strs2[0]));
					// 不是广告的稿件，才设置下面这些值
					if (!progm2GaoJian.getManuscript().isAdv()) {
						progm2GaoJian.setKouBo(StringUtil.isEmpty(strs2[3])
								|| "undefined".equals(strs2[3]) ? null : (","
								+ strs2[3] + ","));
						progm2GaoJian.setDaoYu(StringUtil.isEmpty(strs2[4])
								|| "undefined".equals(strs2[4]) ? null : (","
								+ strs2[4] + ","));
						progm2GaoJian.setBianHouYu(StringUtil.isEmpty(strs2[5])
								|| "undefined".equals(strs2[5]) ? null : (","
								+ strs2[5] + ","));
						progm2GaoJian.setTiYao(strs2[6]);
						progm2GaoJian.setJiaoBiao(strs2[7]);
					}
					progm2GaoJian.setOrder(i + 1);
					dao.insertOrUpdate(progm2GaoJian);
				} else {
					// 如果为空，则出错了
					throw new MsgException("稿件出错了，请重新选择。");
				}
			} else if (Integer.parseInt(strs2[0]) == 0) {
				// new 一个稿件对象，设置title,timeLong
				// new 一个编排的对象，设置顺序号
				Progm2GaoJian progm2GaoJian = new Progm2GaoJian();
				Manuscript manuscript = new Manuscript();
				manuscript.setTitle(strs2[1]);
				manuscript.setTimeLong(Long.parseLong(strs2[2]));
				manuscript.setAdv(true);
				manuscript.setCreateDate(DateUtil.now());
				manuscript.setUser(curUser());
				// 非稿件内容的记录，插入后不用审核
				manuscript.setAuditZt(3);
				dao.insertOrUpdate(manuscript);
				progm2GaoJian.setManuscript(manuscript);
				progm2GaoJian.setProgramming(programming);
				progm2GaoJian.setOrder(i + 1);
				dao.insertOrUpdate(progm2GaoJian);
			}
		}
		// 删除剩余没有再次编排的稿件
		for (Iterator<Progm2GaoJian> it = map.values().iterator(); it.hasNext();) {
			// TODO 移除稿件时，稿件的使用次数是否是减少1?
			// manuscript.setTimes(manuscript.getTimes()-1);
			dao.delete(it.next());
		}
	}

	/**
	 * 将根据user的id字符串转换成name字符串，用于前台显示
	 * 
	 * @param str
	 * @return
	 * @since chendan 2010-3-14
	 */
	public String parseUesrIdToName(String str) {
		StringBuilder name = new StringBuilder();
		if (!StringUtil.isEmpty(str)) {
			String[] id = str.split(",");
			Set<String> idSet = Sets.newHashSet();
			for (int i = 0; i < id.length; i++) {
				// 对于重复的人员，不重复保存
				if (!StringUtil.isEmpty(id[i]) && !idSet.contains(id[i])) {
					idSet.add(id[i]);
					String hql = "select u.name from com.monlyu.vo.User u where u.id=?";
					name.append(dao.findOne(hql, Long.parseLong(id[i])) + "|");
				}
			}
		}
		return name.toString().length() <= 0 ? name.toString()
				: (String) StringUtil.shot(name.toString(), name.toString()
						.length() - 1);
	}

	/**
	 * 保存新闻编排人员信息
	 * 
	 * @param proStaffInfo
	 * @since chendan 2010-2-16
	 */
	public void editProStaff(ProStaffInfo proStaffInfo) {
		if (!roleBo.checkPermission(PermVar.PROGRAMMING_STAFF_MODIFY)) {
			throw new MsgException("对不起，您没有栏目人员维护的权限。");
		}
		ProStaffInfo dbPsfInfo = dao.get(ProStaffInfo.class, proStaffInfo
				.getId());

		dbPsfInfo
				.setSysJianZhi(proStaffInfo.getSysJianZhi().getId() == null ? null
						: (User) dao.get(User.class, proStaffInfo
								.getSysJianZhi().getId()));
		dbPsfInfo
				.setJianZhi(proStaffInfo.getJianZhi().getId() == null ? null
						: (User) dao.get(User.class, proStaffInfo.getJianZhi()
								.getId()));
		dbPsfInfo.setDaoBo(proStaffInfo.getDaoBo().getId() == null ? null
				: (User) dao.get(User.class, proStaffInfo.getDaoBo().getId()));
		dbPsfInfo
				.setSysEditor(proStaffInfo.getSysEditor().getId() == null ? null
						: (User) dao.get(User.class, proStaffInfo
								.getSysEditor().getId()));
		dbPsfInfo
				.setEditor1(proStaffInfo.getEditor1().getId() == null ? null
						: (User) dao.get(User.class, proStaffInfo.getEditor1()
								.getId()));
		dbPsfInfo
				.setEditor2(proStaffInfo.getEditor2().getId() == null ? null
						: (User) dao.get(User.class, proStaffInfo.getEditor2()
								.getId()));
		dbPsfInfo
				.setEditor3(proStaffInfo.getEditor3().getId() == null ? null
						: (User) dao.get(User.class, proStaffInfo.getEditor3()
								.getId()));
		dbPsfInfo
				.setEditor4(proStaffInfo.getEditor4().getId() == null ? null
						: (User) dao.get(User.class, proStaffInfo.getEditor4()
								.getId()));
		List<User> users = Lists.newArrayList();
		if (proStaffInfo.getBroadcast1().getId() == null) {
			dbPsfInfo.setBroadcast1(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getBroadcast1()
					.getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setBroadcast1(user);
		}
		if (proStaffInfo.getBroadcast2().getId() == null) {
			dbPsfInfo.setBroadcast2(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getBroadcast2()
					.getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setBroadcast2(user);
		}
		if (proStaffInfo.getBroadcast3().getId() == null) {
			dbPsfInfo.setBroadcast3(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getBroadcast3()
					.getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setBroadcast3(user);
		}
		if (proStaffInfo.getBroadcast4().getId() == null) {
			dbPsfInfo.setBroadcast4(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getBroadcast4()
					.getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setBroadcast4(user);
		}
		// 修改出像人员的打分表
		staffScoreBo.createStaffScore(users, proStaffInfo.getProgramming(),
				"photo");
		// 清空Users
		users.removeAll(users);
		// 制作人员
		if (proStaffInfo.getMaker1().getId() == null) {
			dbPsfInfo.setMaker1(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getMaker1().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setMaker1(user);
		}
		if (proStaffInfo.getMaker2().getId() == null) {
			dbPsfInfo.setMaker2(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getMaker2().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setMaker2(user);
		}
		if (proStaffInfo.getMaker3().getId() == null) {
			dbPsfInfo.setMaker3(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getMaker3().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setMaker3(user);
		}
		if (proStaffInfo.getMaker4().getId() == null) {
			dbPsfInfo.setMaker4(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getMaker4().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setMaker4(user);
		}
		// 修改制作人员的打分表
		staffScoreBo.createStaffScore(users, proStaffInfo.getProgramming(),
				"maker");
		// 清空Users
		users.removeAll(users);
		// 灯光
		if (proStaffInfo.getLightor1().getId() == null) {
			dbPsfInfo.setLightor1(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getLightor1().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setLightor1(user);
		}
		if (proStaffInfo.getLightor2().getId() == null) {
			dbPsfInfo.setLightor2(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getLightor2().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setLightor2(user);
		}
		// 修改灯光人员的打分表
		staffScoreBo.createStaffScore(users, proStaffInfo.getProgramming(),
				"light");
		// 清空Users
		users.removeAll(users);
		// 字幕
		if (proStaffInfo.getZiMu().getId() == null) {
			dbPsfInfo.setZiMu(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getZiMu().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setZiMu(user);
		}
		if (proStaffInfo.getZiMu2().getId() == null) {
			dbPsfInfo.setZiMu2(null);
		} else {
			User user = dao.get(User.class, proStaffInfo.getZiMu2().getId());
			if (user != null) {
				users.add(user);
			}
			dbPsfInfo.setZiMu2(user);
		}
		// 修改字幕的打分表
		staffScoreBo.createStaffScore(users, proStaffInfo.getProgramming(),
				"zimu");
		dao.insertOrUpdate(dbPsfInfo);
	}

	/**
	 * 查询新闻编排人员信息
	 * 
	 * @param programming
	 * @return
	 * @since chendan 2010-2-16
	 */
	public ProStaffInfo searchProStaffInfo(Programming programming) {
		String hql = "from com.monlyu.vo.ProStaffInfo p where p.programming.id=?";
		return (ProStaffInfo) dao.findOne(hql, programming.getId());
	}

	/**
	 * 查找稿件 <br>
	 * 
	 * @param manuscript
	 * @param beginDate
	 * @param endDate
	 * @param programming
	 * @param used
	 *            TODO
	 * @return 第一个为剩余待选稿件,第二个为查询的栏目已选择稿件
	 * @since chendan 2010-2-23
	 */
	public Object[] getManuscript(Manuscript manuscript, Date beginDate,
			Date endDate, Programming programming, int used) {
		// 查找已选择稿件
		String hqlProgram = "select m.id,m.auditZt,m.title,m.timeLong,m.times from com.monlyu.vo.Progm2GaoJian p,"
				+ "com.monlyu.vo.Manuscript m where p.manuscript.id=m.id and p.programming.id=? order by p.order";
		List programList = dao.find(hqlProgram, programming.getId());
		// 查找待选稿件
		StringBuilder hql = new StringBuilder();
		hql
				.append("select m.id,m.auditZt,m.title,m.timeLong,m.times from com.monlyu.vo.Manuscript m"
						+ " where adv=false and m.auditZt=? ");
		List<Object> args = new ArrayList<Object>();
		args.add(Manuscript.STATUS_DONE);
		if (manuscript != null) {
			if (manuscript.getColumn() > 0) {
				hql.append(" and m.column=?");
				args.add(manuscript.getColumn());
			}
			if (!StringUtil.isEmpty(manuscript.getTitle())) {
				hql.append(" and m.title like ?");
				args.add("%" + manuscript.getTitle() + "%");
			}
		}
		if (beginDate != null) {
			hql.append(" and m.createDate>=?");
			args.add(beginDate);
		}
		if (endDate != null) {
			hql.append(" and m.createDate<=?");
			args.add(DateUtil.addDay(endDate, 1));
		}
		if (used == 1) {
			hql.append(" and m.times>0");
		} else if (used == 2) {
			hql.append(" and m.times=0");
		}
		// 排除该栏目已经选择的稿件
		hql
				.append(" and not exists(select p.id from com.monlyu.vo.Progm2GaoJian p "
						+ " where p.manuscript.id=m.id and p.programming.id=?)");
		args.add(programming.getId());
		List result = dao.find(hql.toString(), args.toArray());
		return new Object[] { composeMsModel(result),
				composeMsModel(programList) };
	}

	/**
	 * 组合ManuscriptModel的list对象
	 * 
	 * @param result
	 * @return
	 * @since chendan 2010-2-24
	 */
	private List<ManuscriptModel> composeMsModel(List result) {
		List<ManuscriptModel> model = Lists.newArrayList();
		for (Iterator it = result.iterator(); it.hasNext();) {
			Object[] objects = (Object[]) it.next();
			ManuscriptModel manModel = new ManuscriptModel();
			manModel.setId((Long) objects[0]);
			manModel.setAuditZt(((Integer) objects[1]).intValue());
			manModel.setTitle((String) objects[2]);
			manModel.setTimeLong((Long) objects[3]);
			manModel.setUserName(getManuscriptReporter(manModel.getId()));
			manModel.setTimes((Integer) objects[4]);
			model.add(manModel);
		}
		return model;
	}

	/**
	 * 根据Id加载programming对象
	 * 
	 * @param programId
	 * @return
	 * @since chendan 2010-2-27
	 */
	public Programming getProgramming(Long programId) {
		return (Programming) dao.findOne(
				"from com.monlyu.vo.Programming p where p.id=?", programId);
	}

	/**
	 * 获取新闻播出单打印信息
	 * 
	 * @param programming
	 * @return
	 * @since chendan 2010-3-4
	 */
	public ProgrammingModel getProgrammingModel(Programming programming) {
		if (programming == null || programming.getId() == null) {
			throw new MsgException("新闻编排栏目选择有误");
		}
		programming = getProgramming(programming.getId());
		ProgrammingModel prgModel = new ProgrammingModel();
		// 查询新闻栏目人员
		String hqlps = "from com.monlyu.vo.ProStaffInfo ps where ps.programming.id=?";
		ProStaffInfo pStaffInfo = (ProStaffInfo) dao.findOne(hqlps, programming
				.getId());
		// 查询串联单信息
		String hql = "select distinct( pg.order),pg.tiYao,pg.kouBo,pg.daoYu,pg.bianHouYu,"
				+ " m.level,pg.jiaoBiao,m.title,m.timeLong,m.user.name"
				+ " from com.monlyu.vo.Programming p,com.monlyu.vo.Manuscript m,"
				+ " com.monlyu.vo.Progm2GaoJian pg,com.monlyu.vo.User u where "
				+ " pg.programming.id=p.id and pg.manuscript.id=m.id  and p.id=? order by pg.order ";
		List objList = dao.find(hql, programming.getId());
		prgModel.setDate(DateUtil.format(programming.getDate()));
		prgModel.setColumn(enumsBo.getEnumValue(programming.getColumn())
				.toString());
		if (pStaffInfo != null) {
			prgModel.setSysJianZhi(pStaffInfo.getSysJianZhi() == null ? ""
					: pStaffInfo.getSysJianZhi().getName());
			prgModel.setJianZhi(pStaffInfo.getJianZhi() == null ? ""
					: pStaffInfo.getJianZhi().getName());
			prgModel.setDaoBo(pStaffInfo.getDaoBo() == null ? "" : pStaffInfo
					.getDaoBo().getName());
			prgModel.setSysEditor(pStaffInfo.getSysEditor() == null ? ""
					: pStaffInfo.getSysEditor().getName());
			StringBuilder editor = new StringBuilder();
			if (pStaffInfo.getEditor1() != null) {
				editor.append(pStaffInfo.getEditor1().getName() + "|");
			}
			if (pStaffInfo.getEditor2() != null) {
				editor.append(pStaffInfo.getEditor2().getName() + "|");
			}
			if (pStaffInfo.getEditor3() != null) {
				editor.append(pStaffInfo.getEditor3().getName() + "|");
			}
			if (pStaffInfo.getEditor4() != null) {
				editor.append(pStaffInfo.getEditor4().getName() + "|");
			}
			prgModel.setEditor(editor.toString());
			StringBuilder broadcast = new StringBuilder();
			if (pStaffInfo.getBroadcast1() != null) {
				broadcast.append(pStaffInfo.getBroadcast1().getName() + "|");
			}
			if (pStaffInfo.getBroadcast2() != null) {
				broadcast.append(pStaffInfo.getBroadcast2().getName() + "|");
			}
			if (pStaffInfo.getBroadcast3() != null) {
				broadcast.append(pStaffInfo.getBroadcast3().getName() + "|");
			}
			if (pStaffInfo.getBroadcast4() != null) {
				broadcast.append(pStaffInfo.getBroadcast4().getName() + "|");
			}
			prgModel.setBroadcast(broadcast.toString());
			StringBuilder maker = new StringBuilder();
			if (pStaffInfo.getMaker1() != null) {
				maker.append(pStaffInfo.getMaker1().getName() + "|");
			}
			if (pStaffInfo.getMaker2() != null) {
				maker.append(pStaffInfo.getMaker2().getName() + "|");
			}
			if (pStaffInfo.getMaker3() != null) {
				maker.append(pStaffInfo.getMaker3().getName() + "|");
			}
			if (pStaffInfo.getMaker4() != null) {
				maker.append(pStaffInfo.getMaker4().getName() + "|");
			}
			prgModel.setMaker(maker.toString());
			StringBuilder lightor = new StringBuilder();
			if (pStaffInfo.getLightor1() != null) {
				lightor.append(pStaffInfo.getLightor1().getName() + "|");
			}
			if (pStaffInfo.getLightor2() != null) {
				lightor.append(pStaffInfo.getLightor2().getName() + "|");
			}
			prgModel.setLightor(lightor.toString());
			StringBuilder zimu = new StringBuilder();
			if (pStaffInfo.getZiMu() != null) {
				zimu.append(pStaffInfo.getZiMu().getName() + "|");
			}
			if (pStaffInfo.getZiMu2() != null) {
				zimu.append(pStaffInfo.getZiMu2().getName() + "|");
			}
			prgModel.setZiMu(zimu.toString());
		}
		List<Program2GaoJianModel> list = Lists.newArrayList();
		List<String> tiYaoList = Lists.newArrayList();
		for (Iterator it = objList.iterator(); it.hasNext();) {
			Object[] object = (Object[]) it.next();
			Program2GaoJianModel pgModel = new Program2GaoJianModel();
			int num = 0;
			pgModel.setOrder((Integer) object[num++]);
			if (!StringUtil.isEmpty(object[num])) {
				tiYaoList.add((String) object[num]);
			}
			num++;
			String temp = parseUesrIdToName((String) object[num]);
			pgModel.setKouBo(StringUtil.isEmpty(temp) ? "--" : temp);
			num++;
			temp = parseUesrIdToName((String) object[num]);
			pgModel.setDaoYu(StringUtil.isEmpty(temp) ? "--" : temp);
			num++;
			temp = parseUesrIdToName((String) object[num]);
			pgModel.setBianHouYu(StringUtil.isEmpty(temp) ? "--" : temp);
			num++;
			pgModel.setLevel(StringUtil.isEmpty(object[num]) ? null
					: (Long) object[num]);
			num++;
			pgModel.setJiaoBiao(StringUtil.isEmpty(object[num]) ? "--"
					: (String) object[num]);
			num++;
			pgModel.setTitle((String) object[num++]);
			pgModel.setTimeLong(StringUtil.isEmpty(object[num]) ? null
					: (Long) object[num]);
			num++;
			pgModel.setUserName(StringUtil.isEmpty(object[num]) ? "--"
					: (String) object[num]);
			list.add(pgModel);
		}
		prgModel.setProgram2GaoJianModel(list);
		prgModel.setTiYao(tiYaoList);
		prgModel.setToday(DateUtil.now());
		prgModel.setCurUserName(curUser().getName());
		return prgModel;
	}

	/**
	 * 导出编排串联单
	 * 
	 * @param programming
	 * @return
	 * @throws Exception
	 * @since chendan 2010-2-28
	 */
	public InputStream exportProgram(Programming programming) throws Exception {
		if (programming == null || programming.getId() == null) {
			throw new MsgException("新闻编排栏目选择有误");
		}
		programming = getProgramming(programming.getId());
		// 查询新闻栏目人员
		String hqlps = "from com.monlyu.vo.ProStaffInfo ps where ps.programming.id=?";
		ProStaffInfo pStaffInfo = (ProStaffInfo) dao.findOne(hqlps, programming
				.getId());
		// // 查询串联单信息
		// String hql = "select distinct(
		// pg.order),e.key,m.title,m.user.name,m.level,m.unit,pg.tiYao from
		// com.monlyu.vo.Programming p,com.monlyu.vo.Manuscript m,"
		// + "com.monlyu.vo.Enums e,com.monlyu.vo.Progm2GaoJian
		// pg,com.monlyu.vo.User u where "
		// + "pg.programming.id=p.id and pg.manuscript.id=m.id and pg.kouBo=e.id
		// and p.id=? order by pg.order ";
		List objList = searchProgm2GaoJian(programming.getId());
		// 拿到导出的表样对象流
		String url = WebOptUtil.APP_ARGS.getWebFileDir()
				+ "common/report/programming.xls";
		InputStream is = new FileInputStream(url);
		HSSFWorkbook wb = new HSSFWorkbook(is);
		is.close();
		HSSFSheet sheet = wb.getSheetAt(0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		style.setFont(font);
		style.setWrapText(true);
		int rowNum = 0;
		short celNum = 0;
		HSSFRow row = sheet.createRow(rowNum++);
		// 下面开始组装数据
		HSSFCell cell = row.createCell(celNum);
		cell.setCellValue(new HSSFRichTextString("《"
				+ enumsBo.getEnumValue(programming.getColumn()) + "》每日稿件串播表"));
		cell.setCellStyle(style);
		// 第二行
		row = sheet.createRow(rowNum++);
		cell = row.createCell(celNum);
		StringBuilder pstf = new StringBuilder();
		pstf.append("【责任编辑】：");
		if (pStaffInfo != null && pStaffInfo.getSysEditor() != null) {
			pstf.append(pStaffInfo.getSysEditor().getName() + "  ");
		}
		pstf.append("【播音】：");
		if (pStaffInfo != null && pStaffInfo.getBroadcast1() != null) {
			pstf.append(pStaffInfo.getBroadcast1().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getBroadcast2() != null) {
			pstf.append(pStaffInfo.getBroadcast2().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getBroadcast3() != null) {
			pstf.append(pStaffInfo.getBroadcast3().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getBroadcast4() != null) {
			pstf.append(pStaffInfo.getBroadcast4().getName() + "  ");
		}
		pstf.append("【制作】：");
		if (pStaffInfo != null && pStaffInfo.getMaker1() != null) {
			pstf.append(pStaffInfo.getMaker1().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getMaker2() != null) {
			pstf.append(pStaffInfo.getMaker2().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getMaker3() != null) {
			pstf.append(pStaffInfo.getMaker3().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getMaker4() != null) {
			pstf.append(pStaffInfo.getMaker4().getName() + "  ");
		}
		pstf.append("【监制】：");
		if (pStaffInfo != null && pStaffInfo.getJianZhi() != null) {
			pstf.append(pStaffInfo.getJianZhi().getName() + "  ");
		}
		pstf.append("【总监制】：");
		if (pStaffInfo != null && pStaffInfo.getSysJianZhi() != null) {
			pstf.append(pStaffInfo.getSysJianZhi().getName() + "  ");
		}
		cell.setCellValue(new HSSFRichTextString(pstf.toString()));
		cell.setCellStyle(style);
		// 导播1，编辑4，灯光2，字幕2
		// 第三行
		// 清空字符串，重新组装，放到第三行
		pstf = new StringBuilder();
		row = sheet.createRow(rowNum++);
		cell = row.createCell(celNum);
		cell.setCellStyle(style);
		pstf.append("【导播】：");
		if (pStaffInfo != null && pStaffInfo.getDaoBo() != null) {
			pstf.append(pStaffInfo.getDaoBo().getName() + "  ");
		}
		pstf.append("【编辑】：");
		if (pStaffInfo != null && pStaffInfo.getEditor1() != null) {
			pstf.append(pStaffInfo.getEditor1().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getEditor2() != null) {
			pstf.append(pStaffInfo.getEditor2().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getEditor3() != null) {
			pstf.append(pStaffInfo.getEditor3().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getEditor4() != null) {
			pstf.append(pStaffInfo.getEditor4().getName() + "  ");
		}
		pstf.append("【灯光】：");
		if (pStaffInfo != null && pStaffInfo.getLightor1() != null) {
			pstf.append(pStaffInfo.getLightor1().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getLightor2() != null) {
			pstf.append(pStaffInfo.getLightor2().getName() + "  ");
		}
		pstf.append("【字幕】：");
		if (pStaffInfo != null && pStaffInfo.getZiMu() != null) {
			pstf.append(pStaffInfo.getZiMu().getName() + "  ");
		}
		if (pStaffInfo != null && pStaffInfo.getZiMu2() != null) {
			pstf.append(pStaffInfo.getZiMu2().getName() + "  ");
		}
		cell.setCellValue(new HSSFRichTextString(pstf.toString()));

		// 第四行
		row = sheet.createRow(rowNum++);
		cell = row.createCell(celNum);
		cell.setCellValue(new HSSFRichTextString("播出时间："
				+ DateUtil.format(programming.getDate(), "yyyy年MM月dd日")));
		cell.setCellStyle(style);
		rowNum++;
		rowNum++;
		int tiYaoRow = rowNum + objList.size();
		int tiYaoNum = 0;
		for (Iterator<Progm2GaoJian> it = objList.iterator(); it.hasNext();) {
			Progm2GaoJian pGaoJian = it.next();
			celNum = 0;
			row = sheet.createRow(rowNum++);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_NUMERIC);
			cell.setCellValue(pGaoJian.getOrder()); // 序号
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(pGaoJian.getKouBoName())); // 口播
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(pGaoJian.getDaoYuName())); // 导语
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(pGaoJian
					.getBianHouYuName())); // 编后语
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(pGaoJian.getManuscript()
					.getTitle()));// 标题
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(pGaoJian.getJiaoBiao()));// 角标
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(pGaoJian.getManuscript()
					.getReportorName()));// 记者
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(pGaoJian.getManuscript()
					.getTimeLong()
					+ "秒")); // 配音长度
			cell.setCellStyle(style);
			cell = row.createCell(celNum++, HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString((String) enumsBo
					.getEnumValue(pGaoJian.getManuscript().getUnit()))); // 报道单位
			cell.setCellStyle(style);
			if (!StringUtil.isEmpty(pGaoJian.getTiYao())) {
				tiYaoNum++;
				short num = 4;
				row = sheet.createRow(tiYaoRow + tiYaoNum - 1);
				cell = row.createCell((short) 0);
				cell.setCellStyle(style);
				cell = row.createCell((short) 1);
				cell.setCellStyle(style);
				cell = row.createCell((short) 2);
				cell.setCellStyle(style);
				cell = row.createCell((short) 3);
				cell.setCellStyle(style);
				cell = row.createCell(num++, HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(new HSSFRichTextString(pGaoJian.getTiYao()));
				cell.setCellStyle(style);
				cell = row.createCell(num++, HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(new HSSFRichTextString(""));
				cell.setCellStyle(style);
				cell = row.createCell(num++, HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(new HSSFRichTextString(""));
				cell.setCellStyle(style);
				cell = row.createCell(num++, HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(new HSSFRichTextString(""));
				cell.setCellStyle(style);
				cell = row.createCell(num++, HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(new HSSFRichTextString(""));
				cell.setCellStyle(style);
			}
		}
		// 提要
		row = sheet.getRow(tiYaoRow);
		HSSFCellStyle style1 = wb.createCellStyle();
		style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style1.setFont(font);
		style1.setWrapText(true);
		style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		cell = row.createCell((short) 0);
		cell.setCellValue(new HSSFRichTextString("提要"));
		cell.setCellStyle(style1);
		// 设置合并单元格
		sheet
				.addMergedRegion(new Region(tiYaoRow, (short) 0,
						tiYaoNum == 0 ? tiYaoRow : (tiYaoRow + tiYaoNum - 1),
						(short) 3));
		row = sheet
				.getRow(tiYaoNum == 0 ? tiYaoRow : (tiYaoRow + tiYaoNum - 1));
		cell = row.getCell((short) 0);
		cell.setCellStyle(style);
		cell = row.getCell((short) 1);
		cell.setCellStyle(style);
		cell = row.getCell((short) 2);
		cell.setCellStyle(style);
		cell = row.getCell((short) 3);
		cell.setCellStyle(style);

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		wb.write(os);
		return new ByteArrayInputStream(os.toByteArray());
	}

	/**
	 * 查询稿件，为稿件打分
	 * 
	 * @param searchManuscriptModel
	 * @return
	 * @since chendan 2010-3-5
	 */
	public List<GradeManuscriptModel> getManuscript(
			SearchManuscriptModel searchManuscriptModel) {
		List<GradeManuscriptModel> GradeManuscriptModels = Lists.newArrayList();
		StringBuilder hql = new StringBuilder();
		List<Object> args = new ArrayList<Object>();
		hql
				.append("from com.monlyu.vo.Manuscript m where m.adv=false and m.times>0 and m.auditZt=? ");
		args.add(Manuscript.STATUS_DONE);
		if (searchManuscriptModel != null) {
			if (!StringUtil.isEmpty(searchManuscriptModel.getUserId())) {
				// String[] name =
				// searchManuscriptModel.getUserName().split(",");
				hql
						.append(" and exists(select g.id from com.monlyu.vo.GaoJian2Reporter g "
								+ "where g.manuscript.id=m.id and  g.reporter.id=?) ");
				args.add(searchManuscriptModel.getUserId());
				// hql.append("(g.reporter.name like ? ");
				// args.add(Long.parseLong(name[0]));
				// for (int i = 1; i < name.length; i++) {
				// hql.append(" or g.reporter.id= ?");
				// args.add(Long.parseLong(name[i]));
				// }
				// hql.append("))");
			}
			if (searchManuscriptModel.getColumn() != null
					&& searchManuscriptModel.getColumn().intValue() > 0) {
				hql.append(" and m.column=?");
				args.add(searchManuscriptModel.getColumn());
			}
			if (searchManuscriptModel.getBeginDate() != null) {
				hql.append(" and m.createDate>=?");
				args.add(searchManuscriptModel.getBeginDate());
			}
			if (searchManuscriptModel.getEndDate() != null) {
				hql.append(" and m.createDate<=?");
				args
						.add(DateUtil.addDay(
								searchManuscriptModel.getEndDate(), 1));
			}
			if (searchManuscriptModel.getUbeginDate() != null) {
				hql.append(" and m.usedDate>=?");
				args.add(searchManuscriptModel.getUbeginDate());
			}
			if (searchManuscriptModel.getUendDate() != null) {
				hql.append(" and m.usedDate<=?");
				args.add(DateUtil
						.addDay(searchManuscriptModel.getUendDate(), 1));
			}
			if (searchManuscriptModel.getOwetype() != null
					&& searchManuscriptModel.getOwetype().intValue() > 0) {
				hql.append(" and m.owetype=?");
				args.add(searchManuscriptModel.getOwetype());
			}
			if (searchManuscriptModel.getCategory() != null
					&& searchManuscriptModel.getCategory().intValue() > 0) {
				hql.append(" and m.category=?");
				args.add(searchManuscriptModel.getCategory());
			}
			if (searchManuscriptModel.getBcType() != null
					&& searchManuscriptModel.getBcType().intValue() > 0) {
				hql.append(" and m.bcType=?");
				args.add(searchManuscriptModel.getBcType());
			}
			if (!StringUtil.isEmpty(searchManuscriptModel.getTitle())) {
				hql.append(" and (m.title like ? or m.content like ?)");
				args.add("%" + searchManuscriptModel.getTitle() + "%");
				args.add("%" + searchManuscriptModel.getTitle() + "%");
			}
		}
		List result = dao.find(hql.toString(), args.toArray());
		for (Iterator<Manuscript> it = result.iterator(); it.hasNext();) {
			Manuscript manuscript = it.next();
			GradeManuscriptModel gManuscriptModel = new GradeManuscriptModel();
			gManuscriptModel.setManuscript(manuscript);
			gManuscriptModel.setUserName(getManuscriptReporter(manuscript
					.getId()));
			String audit = " from com.monlyu.vo.ManuScAudit m where m.manuscript.id=? and m.level=1";
			ManuScAudit manuScAudit = (ManuScAudit) dao.findOne(audit,
					manuscript.getId());
			if (manuScAudit != null) {
				if (manuScAudit.getAuditor() != null) {
					gManuscriptModel.setAuditName(manuScAudit.getAuditor()
							.getName());
				}
				if (manuScAudit.getAuditScore() != null) {
					gManuscriptModel.setAuditScore(manuScAudit.getAuditScore());
				}
			}
			GradeManuscriptModels.add(gManuscriptModel);
		}
		return GradeManuscriptModels;
	}

	/**
	 * 稿件打分
	 * 
	 * @param contentInfo
	 *            稿件的等级和分数
	 * @since chendan 2010-3-5
	 */
	public void editGrade(String contentInfo) {
		if (!roleBo.checkPermission(PermVar.MANUSCRIPT_GRADE)) {
			throw new MsgException("对不起，您没有稿件打等/打分的权限。");
		}
		String[] manscripts = contentInfo.split(";");
		// 先设置稿件的分数
		for (int i = 0; i < manscripts.length; i++) {
			String[] manInfo = manscripts[i].split(",");
			Manuscript manuscript = dao.get(Manuscript.class, Long
					.parseLong(manInfo[0]));
			if (manuscript == null) {
				throw new MsgException("稿件出错了，请刷新页面重新选择");
			}
			manuscript.setLevel(Long.parseLong(manInfo[1]));
			// 稿件分数根据等级自动获取
			manuscript.setScore(Float.parseFloat((String) enumsBo
					.getValue(manuscript.getLevel())));
			// 设置配音人员的分数
			manuscript.setPuserScore(Long.parseLong(manInfo[2]));
			dao.insertOrUpdate(manuscript);
			// 稿件记者的分数根据稿件分数均摊
			String hql2grade = "from com.monlyu.vo.GaoJian2Reporter g where g.manuscript.id=?";
			List gaoJian2Reporters = dao.find(hql2grade, manuscript.getId());
			if (gaoJian2Reporters.size() > 0) {
				float gradeUser = MathUtil.formatFraction(manuscript.getScore()
						* 1.0f / gaoJian2Reporters.size(), 1);
				float fgCount = MathUtil.formatFraction(
						1.0f / gaoJian2Reporters.size(), 1);
				for (Iterator<GaoJian2Reporter> iterator = gaoJian2Reporters
						.iterator(); iterator.hasNext();) {
					GaoJian2Reporter gaoReporter = iterator.next();
					gaoReporter.setScore(gradeUser);
					gaoReporter.setScoreDate(DateUtil.now());
					gaoReporter.setAuditor(curUser());
					gaoReporter.setFgCount(fgCount);
					dao.insertOrUpdate(gaoReporter);
				}
			}

			// 设置稿件编辑的分数
			String audit = " from com.monlyu.vo.ManuScAudit m where m.manuscript.id=? and m.level=1";
			ManuScAudit manuScAudit = (ManuScAudit) dao.findOne(audit,
					manuscript.getId());
			if (manuScAudit != null) {
				manuScAudit.setAuditScore(Long.parseLong(manInfo[3]));
				manuScAudit.setScoreDate(DateUtil.now());
				manuScAudit.setScoreUser(curUser());
				dao.insertOrUpdate(manuScAudit);
			}
		}
	}

	/**
	 * 获取稿件的录用串联单
	 * 
	 * @param manuId
	 * @return
	 * @since ChenDan 2010-8-8
	 */
	public List<Programming> getProgrammingByManus(Long manuId) {
		String hql = "from com.monlyu.vo.Programming p where exists(select pg.id from com.monlyu.vo.Progm2GaoJian pg " +
				" where pg.programming.id=p.id and pg.manuscript.id=?) and p.audit=true ";
		return dao.find(hql, manuId);
	}

	/**
	 * 检测栏目稿件是否已经审核
	 * 
	 * @param programming
	 * @since chendan 2010-3-7
	 */
	public void check(Programming programming) {
		if (programming != null && !programming.isAudit()) {
			throw new MsgException("此串联单还没有审核通过，暂时不能操作");
		}
	}
}
